package com.ambulance.project.biz.controller.manager;

import com.ambulance.common.utils.ResultMapUtil;
import com.ambulance.common.utils.poi.ExcelUtil;
import com.ambulance.framework.aspectj.lang.annotation.Log;
import com.ambulance.framework.aspectj.lang.enums.BusinessType;
import com.ambulance.framework.task.HdTask;
import com.ambulance.framework.web.controller.BaseController;
import com.ambulance.framework.web.domain.AjaxResult;
import com.ambulance.framework.web.page.TableDataInfo;
import com.ambulance.project.biz.dto.admin.ResouceAvaibleDto;
import com.ambulance.project.biz.dto.web.CarHDInfo;
import com.ambulance.project.biz.entity.Statistics;
import com.ambulance.project.biz.service.PatientService;
import com.ambulance.project.biz.service.StatisticsService;
import com.ambulance.project.manager.domain.BizCar;
import com.ambulance.project.manager.domain.BizDispatch;
import com.ambulance.project.manager.service.IBizCarService;
import com.ambulance.project.manager.service.IBizDispatchService;
import com.ambulance.project.manager.utils.MgtCommonUtil;
import com.ambulance.project.manager.utils.MgtUserLoginResult;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDate;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 车辆管理Controller
 *
 * @author zr
 * @date 2020-05-11
 */
@RestController
@RequestMapping("/manager/car")
public class BizCarController extends BaseController {
    @Autowired
    private IBizCarService bizCarService;
    @Autowired
    private HdTask hdTask;
    @Autowired
    private MgtCommonUtil mgtCommonUtil;
    @Autowired
    private IBizDispatchService iBizDispatchService;

    @Value("${hd.webUrl}")
    private String hdWebUrl = "http://211.162.75.141:52467/iVehicleGPS/loginvid.hd";
    @Autowired
    private PatientService patientService;
    @Autowired
    private StatisticsService statisticsService;

    /**
     * 查询车辆管理列表
     */
    //@PreAuthorize("@ss.hasPermi('manager:car:list')")
    @GetMapping("/list")
    public TableDataInfo list(BizCar bizCar) {
        startPage();
        List<BizCar> list = bizCarService.selectBizCarList(bizCar);
        return getDataTable(list);
    }

    /**
     * 查询车辆管理列表
     */
//    //@PreAuthorize("@ss.hasPermi('manager:car:list')")
    @GetMapping("/lists")
    public TableDataInfo lists(BizCar bizCar) {
        List<BizCar> list = bizCarService.selectBizCarList(bizCar);
        return getDataTable(list);
    }

    /**
     * 查询车辆GPS列表
     */
//    //@PreAuthorize("@ss.hasPermi('manager:car:listgps')")
    @GetMapping("/listGps")
    public AjaxResult listGPS(BizCar bizCar) {
        List<BizCar> list = bizCarService.selectBizCarList(bizCar);
        String[] param = {"carID", "vin", "latitude", "longitude"};

        for (BizCar car : list) {
            final CarHDInfo carGpsInfoNoAlarm = hdTask.getCarGpsInfoNoAlarm(String.valueOf(car.getId()));
            car.setLatitude(carGpsInfoNoAlarm.getLatitude());
            car.setLongitude(carGpsInfoNoAlarm.getLongitude());
        }
        return AjaxResult.success(ResultMapUtil.customerObjFields(list, param));
    }

    /**
     * 可用资源列表
     */
//    //@PreAuthorize("@ss.hasPermi('manager:car:listGps')")
    @GetMapping("/resourceNumber")
    public AjaxResult resourceNumber() {
        //获取登陆者id
        final MgtUserLoginResult mgtUserLoginResult = mgtCommonUtil.getMgtUserLoginResult();
        //todo 获取可用资源数量
        final ResouceAvaibleDto resouceAvaibleDto = patientService.listPatientDto(mgtUserLoginResult.getUid());
        return AjaxResult.success(resouceAvaibleDto);
    }

    /**
     * 可用资源列表
     */
//    //@PreAuthorize("@ss.hasPermi('manager:car:listGps')")
    @GetMapping("/statistical")
    public AjaxResult statistical() {
        //获取登陆者id
        final MgtUserLoginResult mgtUserLoginResult = mgtCommonUtil.getMgtUserLoginResult();
        LocalDate localDate = LocalDate.now();
        Integer year = localDate.getYear();
        Integer month = localDate.getMonthValue();
        //上个月
        int LastMonth;
        if (month.equals(1)) {
            LastMonth = 12;
        } else if (month.equals(12)) {
            LastMonth = 1;
        } else {
            LastMonth = month - 1;
        }
        final HashMap<String, Object> returnData = new HashMap<>();
        //本月统计数据
        final List<Statistics> StatistList = statisticsService.list(new QueryWrapper<Statistics>().eq("uid", mgtUserLoginResult.getUid()).eq("year", year).eq("month", month));
        final Object statDatas = getStatDatas(StatistList);
        returnData.put("thisMonth", statDatas);

        //上月统计数据
        final List<Statistics> LastStatistList = statisticsService.list(new QueryWrapper<Statistics>().eq("uid", mgtUserLoginResult.getUid()).eq("year", year).eq("month", LastMonth));
        final Object LaststatDatas = getStatDatas(LastStatistList);
        returnData.put("lastMonth", LaststatDatas);
        return AjaxResult.success(returnData);
    }

    private Object getStatDatas(List<Statistics> StatistList) {
        final HashMap<String, Object> returnData = new HashMap<>();
        // 定义初量 出车次数
        final Map<String, Object> carMapTime = new HashMap<>();
        // 出车时长
        final Map<String, Object> carDuration = new HashMap<>();
        // 救治时长
        final Map<String, Object> teatDuration = new HashMap<>();
        //出车次数
        final ArrayList<String> carMaplist = new ArrayList<>();
        final ArrayList<String> carDurationlist = new ArrayList<>();
        final ArrayList<String> teatDurationlist = new ArrayList<>();
        for (Statistics item : StatistList) {
            carMaplist.add(item.getTime().toString());
            carDurationlist.add(item.getAvgCar().toString());
            teatDurationlist.add(item.getAvgBaseHelp().toString());
        }
        carMapTime.put("name", "出车次数");
        carMapTime.put("data", carMaplist);
        carDuration.put("name", "出车时长");
        carDuration.put("data", carDurationlist);
        teatDuration.put("name", "救治时长");
        teatDuration.put("data", teatDurationlist);
        returnData.put("carNumber", carMapTime);
        returnData.put("carDuration", carDuration);
        returnData.put("teatDuration", teatDuration);
        return returnData;
    }

    /**
     * 导出车辆管理列表
     */
    //@PreAuthorize("@ss.hasPermi('manager:car:export')")
    @Log(title = "车辆管理", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public AjaxResult export(BizCar bizCar) {
        List<BizCar> list = bizCarService.selectBizCarList(bizCar);
        ExcelUtil<BizCar> util = new ExcelUtil<BizCar>(BizCar.class);
        return util.exportExcel(list, "car");
    }

    /**
     * 获取车辆管理详细信息
     */
    //@PreAuthorize("@ss.hasPermi('manager:car:query')")
    @GetMapping(value = "/{carID}")
    public AjaxResult getInfo(@PathVariable("carID") Long carID) {
        return AjaxResult.success(bizCarService.selectBizCarById(carID));
    }

    /**
     * 新增车辆管理
     */
    //@PreAuthorize("@ss.hasPermi('manager:car:add')")
    @Log(title = "车辆管理", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody BizCar bizCar) {
        final MgtUserLoginResult mgtUserLoginResult = mgtCommonUtil.getMgtUserLoginResult();
        bizCar.setUid((long) mgtUserLoginResult.getUid());
        bizCar.setStatus(3);
        bizCar.setScramReason("用户添加,非宏电车辆,无法派遣");
        return toAjax(bizCarService.insertBizCar(bizCar));
    }

    /**
     * 修改车辆管理
     */
    //@PreAuthorize("@ss.hasPermi('manager:car:edit')")
    @Log(title = "车辆管理", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody BizCar bizCar) {
        return toAjax(bizCarService.updateBizCar(bizCar));
    }

    /**
     * 删除车辆管理
     */
    //@PreAuthorize("@ss.hasPermi('manager:car:remove')")
    @Log(title = "车辆管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/{carIDs}")
    public AjaxResult remove(@PathVariable Long[] carIDs) {
        return toAjax(bizCarService.deleteBizCarByIds(carIDs));
    }

    /**
     * 报停车辆
     */
//    //@PreAuthorize("@ss.hasPermi('manager:car:scram')")
    @Log(title = "报停车辆", businessType = BusinessType.UPDATE)
    @PostMapping("/scram")
    public AjaxResult scram(@RequestBody BizCar bizCar) {
        bizCar.setStatus(3);
        return toAjax(bizCarService.updateBizCar(bizCar));
    }

    /**
     * 车辆相关调度记录
     */

    @GetMapping("/dispatchCar/{carID}")
    public AjaxResult dispatchCatInfo(@PathVariable("carID") Long carID) {
        final BizDispatch bizDispatch = new BizDispatch();
        bizDispatch.setCarID(carID);
        final List<BizDispatch> bizDispatches = iBizDispatchService.selectBizDispatchList(bizDispatch);
        String[] param = {"doctor_name", "patient_name", "patient_card", "driver_name", "dispatchID"};
        return AjaxResult.success(ResultMapUtil.customerObjFields(bizDispatches, param));
    }

    /**
     * 获取宏电web地址
     *
     * @return
     */
    @GetMapping(value = "/getHdwebUrl")
    public AjaxResult getHdUrl() {
        return AjaxResult.success(hdWebUrl);
    }
}
